#!/bin/sh
JAVA_HOME=/usr/lib/jvm/java-11-openjdk/bin
MEM_SIZE=512m
APP_HOME=/home/auth/service
JAR_NAME=chaos-auth-service.jar

HEAPDUMP='-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heapdump.hprof'
TRACKING='-XX:NativeMemoryTracking=detail'

PROFILE=$2

is_app_exist() {
  PID=$(ps -ef | grep ${JAR_NAME} | grep -v grep | awk '{print $2}')
  if [ -z "${PID}" ]; then
    # 返回0表示进程不存在
    return 0
  else
    # 返回1表示进程存在
    return 1
  fi
}

start() {
  is_app_exist

  if [ $? -eq "1" ]; then
    echo "app is already running,PID=${PID}"
  else
    cd ${APP_HOME}
    nohup ${JAVA_HOME}/java -Xms${MEM_SIZE} -Xmx${MEM_SIZE} ${HEAPDUMP} ${TRACKING}  \
      -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \
      -jar ${APP_HOME}/${JAR_NAME} --spring.profiles.active=base,${PROFILE} >/dev/null 2>&1 &
    echo "app start,PID=${!}"
  fi
}

debug() {
  is_app_exist

  if [ $? -eq "1" ]; then
    echo "app is already running,PID=${PID}"
  else
    cd ${APP_HOME}
    nohup ${JAVA_HOME}/java -Xms${MEM_SIZE} -Xmx${MEM_SIZE} \
    -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \
    -jar ${APP_HOME}/${JAR_NAME} --spring.profiles.active=base,${PROFILE} >${APP_HOME}/log.log 2>&1 &
    echo "app start,PID=${!}"
  fi
}

stop() {
  is_app_exist
  if [ $? -eq "1" ]; then
    kill ${PID}
    is_app_exist
    if [ $? -eq "1" ]; then
      echo "app force stop"
      kill -9 ${PID}
    fi
    echo "app stop"
  else
    echo "app is not running"
  fi
}

restart() {
  stop
  start
}

status() {
  is_app_exist
  if [ $? -eq "1" ]; then
    echo "app is running, PID=${PID}"
  else
    echo "app is not running"
  fi
}

deploy() {
    echo '正在部署'${JAR_NAME}

    cd ${APP_HOME}
    if [ ! -f package.tgz ]; then
        echo '无可用package'
        exit 1
    fi

    rm -f ${JAR_NAME}

    tar -zxvf package.tgz

    if [ ! -f ${JAR_NAME} ]; then
        echo '无可用jar'
        exit 1
    fi

    ./boot.sh restart ${PROFILE}

    rm -f package.tgz
    echo '完成部署'${JAR_NAME}

}

case $1 in
"debug")
  debug
  ;;
"start")
  start
  ;;
"stop")
  stop
  ;;
"restart")
  restart
  ;;
"status")
  status
  ;;
"deploy")
  deploy
  ;;
esac
exit 0
